package com.esun.rabbit2.viewer.mainact;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.config.Language;
import com.esun.model.LoadingInfo;
import com.esun.model.UserInfo;
import com.esun.network.ConnectionChangeReceiver;
import com.esun.rabbit2.communicaters.recharg.RechargeUserInfo;
import com.esun.rabbit2.communicaters.update.UpdateCheckCommunicater;
import com.esun.rabbit2.viewer.LoginAct;
import com.esun.rabbit2.viewer.MainAct;
import com.esun.rabbit2.viewer.RegistAct;
import com.esun.rabbit2.viewer.mainact.optionact.AboutAct;
import com.esun.rabbit2.viewer.mainact.optionact.HelpListAct;
import com.esun.rabbit2.viewer.mainact.optionact.InviteAct;
import com.esun.rabbit2.viewer.mainact.optionact.PushAct;
import com.esun.rabbit2.viewer.mainact.optionact.UserFeedbackAct;
import com.esun.rabbit2.viewer.mainact.optionact.ValuesManager;
import com.esun.ui.R;
import com.esun.ui.R.color;
import com.esun.util.GetUri;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;
import com.esun.util.magic.magic;
import com.esun.util.md5.MD5;

/**
 * @Title: OptionAct.java
 * @Package com.esun.rabbit2.viewer.mainact
 * @Description: (设置界面)
 * @author Billy qigs@500wan.com
 * @date 2011-5-24 下午04:04:21 copy right 深圳市易讯天空网络技术有限公司
 */
public class OptionAct extends Activity implements OnClickListener, OnCheckedChangeListener {
	private RelativeLayout relativeLoad;// 登录
	private RelativeLayout relativeCallService;// 拨打客服
	private RelativeLayout relativeCheckUpdate;// 检测更新
	private RelativeLayout relativeHelp;// 帮助
	private RelativeLayout relativeExit;// 退出程序
	private RelativeLayout relativeFeedback;// 用户反馈
	private RelativeLayout relativePush;// Push推送
	private RelativeLayout relativeEvaluation;// 评分
	private RelativeLayout relativeInvite;// 邀请好友
	private RelativeLayout relativeAbout;// 关于
	private RelativeLayout relativeAccountProtect;// 账号保护
	private ImageView imageUpdate;// 升级检测配对的分割线
	private CheckBox cbxAccountProtect;
	private TextView tvLogin;
	private TextView tvVersion;
	private TextView tvCheckUpdateMsg;
	private TextView tvPush;
	private ImageView imageViewArrows;
	private ImageView imageViewLogin;
	private Intent intent;
	private ProgressDialog progress;
	private UpdateCheckCommunicater updateCommunicater;
	private Handler handler;

	private Dialog dialog;
	private Button btnDialogSubmit;
	private Button btnDialogcancel;
	private TextView tvDialogMsg;
	private TextView tvTitleMsg;
	private Dialog updateDialog;

	private static final int UPDATE_NEEDED = 10010;
	private static final int UPDATE_NEEDLESS = 10086;
	private static final int CHECK_UPDATE_FAILED = 10100;
	private static final String UPDATE_NEEDLESS_MSG = "您使用的已是最新版本";
	private static final String UPDATE_DIALOG_TITLE = "系统更新";
	private static final String UPDATE_CHECKING_MSG = "正在检测新版本，请稍后...";
	private static final String UPDATE_DIALOG_CONTENT = "检测到新版本，是否更新？";

	private static final String CALL_SERVICE_TEL = "拨打4000-500-500客服电话";
	private static final String CANCELLATION_OR_NOT = "是否注销登录";
	private static final String USE_PROTECT = "1";
	private static final String UNUSE_PROTECT = "0";
	private SQLiteDatabase db;
	private ValuesManager valuesManager;

	public static boolean isLoginSucceed = false;
	public static boolean isShowInputDialog = true;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.option_act);

		initHandler();
		initUI();// 初始化
	}

	/* 按钮监听 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.optionact_relative_login:

			if (UserInfo.getUserInfo().getUserSession().length() < 3) {
				intent.setClass(OptionAct.this, LoginAct.class);
				startActivity(intent);
			} else {
				showDialog(Config.NULLMARK, CANCELLATION_OR_NOT, loginListener);
			}

			break;

		case R.id.optionact_relative_feedback:// 跳到用户反馈Activity

			intent.setClass(OptionAct.this, UserFeedbackAct.class);
			startActivity(intent);

			break;

		case R.id.optionact_relative_invite:// 跳到邀请好友Activity

			intent.setClass(OptionAct.this, InviteAct.class);
			startActivity(intent);

			break;

		case R.id.optionact_relative_push:// 推送

			intent.setClass(OptionAct.this, PushAct.class);
			startActivity(intent);

			break;

		case R.id.optionact_relative_evaluation:// 评价

			Intent intentGetUri = GetUri.getIntent(getApplicationContext());
			if (GetUri.judge(getApplicationContext(), intentGetUri)) {
				Intent goToWebMarket = null;
				goToWebMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("https://market.android.com/details?id=" + OptionAct.this.getPackageName()));
				startActivity(goToWebMarket);

			} else {
				Intent goToMarket = null;
				goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + OptionAct.this.getPackageName()));
				startActivity(goToMarket);

			}

			break;

		case R.id.optionact_relative_about:// 跳到关于Activity

			intent.setClass(OptionAct.this, AboutAct.class);
			startActivity(intent);

			break;

		case R.id.optionact_relative_callService:// 拨打客服

			showDialog(Config.NULLMARK, CALL_SERVICE_TEL, callServiceListener);

			break;

		case R.id.optionact_relative_checkUpdate:// 检查更新

			progress.show();
			checkUpdateThread();

			break;

		case R.id.optionact_relative_exit:// 退出程序

			showDialog(Config.NULLMARK, Language.MSG_QUITDIALOG, quitListener);

			break;

		case R.id.optionact_relative_help:// 帮助

			startActivity(new Intent(OptionAct.this, HelpListAct.class));

			break;

		default:
			break;
		}
	}

	private void showDialog(String title, String msg, OnClickListener l) {
		dialog = new Dialog(this, R.style.dialog);
		dialog.getWindow().setContentView(R.layout.dialog_quit);

		tvTitleMsg = (TextView) dialog.getWindow().findViewById(R.id.dialogquit_tv_title);
		tvTitleMsg.setText(title);
		tvDialogMsg = (TextView) dialog.getWindow().findViewById(R.id.dialogquit_tv_msg);
		tvDialogMsg.setText(msg);
		btnDialogcancel = (Button) dialog.getWindow().findViewById(R.id.dialogquit_btn_cancel);
		btnDialogcancel.setOnClickListener(l);
		btnDialogSubmit = (Button) dialog.getWindow().findViewById(R.id.dialogquit_btn_submit);
		btnDialogSubmit.setOnClickListener(l);

		dialog.show();
	}

	/* 初始化 */
	public void initUI() {

		intent = new Intent();
		relativeLoad = (RelativeLayout) findViewById(R.id.optionact_relative_login);
		relativeLoad.setOnClickListener(this);

		relativeFeedback = (RelativeLayout) findViewById(R.id.optionact_relative_feedback);
		relativeFeedback.setOnClickListener(this);

		relativeCallService = (RelativeLayout) findViewById(R.id.optionact_relative_callService);
		relativeCallService.setOnClickListener(this);

		relativeHelp = (RelativeLayout) findViewById(R.id.optionact_relative_help);
		relativeHelp.setOnClickListener(this);

		relativeCheckUpdate = (RelativeLayout) findViewById(R.id.optionact_relative_checkUpdate);
		relativeCheckUpdate.setOnClickListener(this);

		imageUpdate = (ImageView) findViewById(R.id.optionact_imageview_checkupdate);
		if (!Config.UPDATE_STATE) {
			relativeCheckUpdate.setVisibility(View.GONE);
			imageUpdate.setVisibility(View.GONE);
		}

		relativeExit = (RelativeLayout) findViewById(R.id.optionact_relative_exit);
		relativeExit.setOnClickListener(this);

		relativePush = (RelativeLayout) findViewById(R.id.optionact_relative_push);
		relativePush.setOnClickListener(this);

		relativeEvaluation = (RelativeLayout) findViewById(R.id.optionact_relative_evaluation);
		relativeEvaluation.setOnClickListener(this);

		relativeInvite = (RelativeLayout) findViewById(R.id.optionact_relative_invite);
		relativeInvite.setOnClickListener(this);

		relativeAbout = (RelativeLayout) findViewById(R.id.optionact_relative_about);
		relativeAbout.setOnClickListener(this);

		relativeAccountProtect = (RelativeLayout) findViewById(R.id.optionact_relative_accountProtect);

		cbxAccountProtect = (CheckBox) findViewById(R.id.optionact_cbx_account_protect);
		cbxAccountProtect.setOnCheckedChangeListener(this);
		cbxAccountProtect.setOnClickListener(this);
		cbxAccountProtect.setChecked(UserInfo.getUserInfo().getAccountProtectState());

		tvLogin = (TextView) findViewById(R.id.option_act_tv_login);
		tvCheckUpdateMsg = (TextView) findViewById(R.id.optionact_textview_checkupdate);
		tvVersion = (TextView) findViewById(R.id.optionact_textview_version);
		tvPush = (TextView) findViewById(R.id.optionact_textview_push_status);

		imageViewArrows = (ImageView) findViewById(R.id.optionact_imageview_arrows);
		imageViewLogin = (ImageView) findViewById(R.id.optionact_imageview_login);

		updateCommunicater = new UpdateCheckCommunicater(OptionAct.this);
		progress = ViewerUtil.showProgressDialog(OptionAct.this, UPDATE_CHECKING_MSG);

		if (LoadingInfo.getInstance().getIsupdate() != null) {
			if (LoadingInfo.getInstance().getIsupdate().equals("1")) {
				imageViewArrows.setVisibility(View.GONE);
				tvVersion.setText(LoadingInfo.getInstance().getLatestVersionNum());
				tvVersion.setVisibility(View.VISIBLE);
				tvCheckUpdateMsg.setText("有新版本");
				tvCheckUpdateMsg.setBackgroundColor(color.dark_red);
			} else {
				tvCheckUpdateMsg.setText("检测新更新");
				imageViewArrows.setVisibility(View.VISIBLE);
				tvVersion.setVisibility(View.GONE);
			}

		}

	}

	// 清除用户信息
	public void clearUserInfo() {
		UserInfo.getUserInfo().setUserBalance(Config.NULLMARK);
		UserInfo.getUserInfo().setUserFreeze(Config.NULLMARK);
		UserInfo.getUserInfo().setUserSession(Config.NULLMARK);
		UserInfo.getUserInfo().setUserPwd(Config.NULLMARK);
		UserInfo.getUserInfo().setUserName(Config.NULLMARK);
		UserInfo.getUserInfo().setUserFreeze(Config.NULLMARK);
		RechargeUserInfo.getUserInfo().setSessionId(Config.NULLMARK);
	}

	// 清除数据库
	public void clearDataBase() {
		ContentValues cv = new ContentValues();
		cv.put(Key.KEY_NAME, Config.NULLMARK);
		cv.put(Key.KEY_PASSWORD, Config.NULLMARK);
		cv.put(Key.KEY_SAVE, Config.NUM0);

		db = this.openOrCreateDatabase(Key.KEY_DB_ARABBIT2, MODE_PRIVATE, null);
		db.update(Key.KEY_USERS, cv, "_id=?", new String[] { Config.NUM1 });
		db.close();
	}

	// 更新账户保护状态
	private void updateAccountProtectState(String state) {
		ContentValues cv = new ContentValues();
		cv.put(Key.KEY_ACCOUNTPROTECT, state);

		db = this.openOrCreateDatabase(Key.KEY_DB_ARABBIT2_LOCALCONFIG, MODE_PRIVATE, null);
		db.update(Key.KEY_LOCALCONFIG, cv, "_id=?", new String[] { Config.NUM1 });
		db.close();
	}

	@Override
	protected void onResume() {
		super.onResume();
		this.registerReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver(), ConnectionChangeReceiver.getIntentFilter());

		valuesManager = new ValuesManager(this);
		valuesManager.readValue();
		if (valuesManager.isState_masterPushSwitch()) {
			tvPush.setText("开启");
			tvPush.setTextColor(OptionAct.this.getResources().getColor(R.color.kjxx_red));
		} else {
			tvPush.setText("关闭");
			tvPush.setTextColor(OptionAct.this.getResources().getColor(R.drawable.gray));
		}

		if (UserInfo.getUserInfo().getUserSession().length() < 3) {
			tvLogin.setText(getResources().getString(R.string.login));
			imageViewLogin.setBackgroundResource(R.drawable.set_icon_login_21x21);
			cbxAccountProtect.setEnabled(false);
			relativeAccountProtect.setEnabled(false);
			EDebug.o(this, "cbx ischecked = " + cbxAccountProtect.isChecked() + " cbx isenable = " + cbxAccountProtect.isEnabled());
		} else {
			tvLogin.setText(getResources().getString(R.string.option_zhuxiao));
			tvLogin.setText(getResources().getString(R.string.option_zhuxiao));
			imageViewLogin.setBackgroundResource(R.drawable.set_icon_exit_21x21);
			cbxAccountProtect.setEnabled(true);
			relativeAccountProtect.setEnabled(true);
			EDebug.o(this, "cbx ischecked = " + cbxAccountProtect.isChecked() + " cbx isenable = " + cbxAccountProtect.isEnabled());
		}

		if (isLoginSucceed) {
			((MainAct) this.getParent()).setChildActivity(MainAct.LOTTERY_HALL_ACTIVITY);
			isLoginSucceed = false;
		}

		if (RegistAct.isRegistSucceed) {
			ViewerUtil.showRegistSucceedDialog(OptionAct.this);
			RegistAct.isRegistSucceed = false;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Activity parent = getParent();
			if (parent != null) {
				parent.onKeyDown(keyCode, event);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onPause() {
		super.onPause();
		this.unregisterReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver());
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {

		case R.id.optionact_cbx_account_protect:

			if (isChecked) {
				UserInfo.getUserInfo().setAccountProtectState(true);
				UserInfo.getUserInfo().setResetInputPasswordTime();
				updateAccountProtectState(USE_PROTECT);
			} else {
				if (isShowInputDialog) {
					cbxAccountProtect.setChecked(true);
					showInputPasswordDialog(cbxAccountProtect);
				} else {
					isShowInputDialog = true;
				}
			}

			break;
		}

	}

	private QuitOnClickListener quitListener = new QuitOnClickListener();

	private class QuitOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {

			case R.id.dialogquit_btn_cancel:

				dialog.dismiss();

				break;

			case R.id.dialogquit_btn_submit:

				MainAct.notifyServer(OptionAct.this);

				android.os.Process.killProcess(android.os.Process.myPid());

				break;

			}
		}
	}

	private LoginOnClickListener loginListener = new LoginOnClickListener();

	private class LoginOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {

			case R.id.dialogquit_btn_cancel:

				dialog.dismiss();

				break;

			case R.id.dialogquit_btn_submit:

				clearUserInfo();
				clearDataBase();
				tvLogin.setText(getResources().getString(R.string.login));
				imageViewLogin.setBackgroundResource(R.drawable.set_icon_login_21x21);
				cbxAccountProtect.setEnabled(false);
				relativeAccountProtect.setEnabled(false);
				dialog.dismiss();

				break;

			}
		}
	}

	private CallServiceOnClickListener callServiceListener = new CallServiceOnClickListener();

	private class CallServiceOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {

			case R.id.dialogquit_btn_cancel:

				dialog.dismiss();

				break;

			case R.id.dialogquit_btn_submit:

				// 如果输入不为空创建打电话的Intent
				Intent phoneIntent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + Config.CUSTOMER_SERVICE_TEL));
				// 启动
				startActivity(phoneIntent);
				dialog.dismiss();

				break;

			}
		}
	}

	private UpdateOnClickListener updateOnClickListener = new UpdateOnClickListener();

	private class UpdateOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {

			case R.id.dialog_update_btn_cancel:

				updateDialog.dismiss();

				break;

			case R.id.dialog_update_btn_submit:

				update(updateCommunicater.getUpdateURL());
				updateDialog.dismiss();

				break;

			}
		}
	}

	/**
	 * @Title: checkUpdateThread
	 * @Description: 检测是否有更新线程
	 * @return: void 返回类型
	 */
	private void checkUpdateThread() {
		new Thread() {

			@Override
			public void run() {
				super.run();

				Message msg = new Message();
				try {

					String imei = magic.getIMEI(OptionAct.this);

					int serverState = updateCommunicater.isUpdateCheckSucceed(imei);

					if (serverState == 100) {
						msg = handler.obtainMessage(UPDATE_NEEDED, null);
					} else if (serverState == 217) {
						msg = handler.obtainMessage(UPDATE_NEEDLESS, null);
					} else {
						msg = handler.obtainMessage(CHECK_UPDATE_FAILED, null);
					}
					handler.sendMessage(msg);
				} catch (Exception e) {
					msg = handler.obtainMessage(Config.CONNECTION_FAIL, null);
					handler.sendMessage(msg);
				}

			}

		}.start();
	}

	private void initHandler() {
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				progress.dismiss();

				switch (msg.what) {

				case UPDATE_NEEDED:

					imageViewArrows.setVisibility(View.GONE);
					tvVersion.setVisibility(View.VISIBLE);
					tvVersion.setText(LoadingInfo.getInstance().getLatestVersionNum());
					tvCheckUpdateMsg.setText("有新版本");
					tvCheckUpdateMsg.setBackgroundColor(color.dark_red);

					String updateMsg = updateCommunicater.getUpdateInfo();
					updateMsg = updateMsg.replace('$', '\n');
					updateDialog = new Dialog(OptionAct.this, R.style.dialog);
					updateDialog.getWindow().setContentView(R.layout.dialog_update);

					tvTitleMsg = (TextView) updateDialog.getWindow().findViewById(R.id.dialog_update_tv_title);
					tvTitleMsg.setText(UPDATE_DIALOG_TITLE);
					tvDialogMsg = (TextView) updateDialog.getWindow().findViewById(R.id.dialog_update_tv_msg);
					tvDialogMsg.setText(UPDATE_DIALOG_CONTENT + '\n' + updateMsg);
					btnDialogcancel = (Button) updateDialog.getWindow().findViewById(R.id.dialog_update_btn_cancel);
					btnDialogcancel.setOnClickListener(updateOnClickListener);
					btnDialogSubmit = (Button) updateDialog.getWindow().findViewById(R.id.dialog_update_btn_submit);
					btnDialogSubmit.setOnClickListener(updateOnClickListener);

					updateDialog.show();

					break;

				case UPDATE_NEEDLESS:
					tvCheckUpdateMsg.setText("检测新更新");
					imageViewArrows.setVisibility(View.VISIBLE);
					tvVersion.setVisibility(View.GONE);
					Toast.makeText(OptionAct.this, UPDATE_NEEDLESS_MSG, Toast.LENGTH_SHORT).show();

					break;

				case CHECK_UPDATE_FAILED:

					ViewerUtil.showTipDialog(OptionAct.this, updateCommunicater.getServerMsg(), false);

					break;

				case Config.CONNECTION_FAIL:

					ViewerUtil.showTipDialog(OptionAct.this, Language.STR_CONNECTIONFAIL, false);

					break;

				default:

					break;
				}

			}
		};
	}

	/**
	 * @Title: update
	 * @Description: 打开webview开始更新
	 */
	private void update(String url) {

		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
		startActivity(intent);

	}

	/**
	 * @Title: showInputPasswordDialog
	 * @Description: 输入密码对话框
	 */
	public void showInputPasswordDialog(final CheckBox cbx) {
		final Dialog inputPwdDialog = new Dialog(OptionAct.this, R.style.dialog);
		inputPwdDialog.getWindow().setContentView(R.layout.dialog_edittext_continuebuyl);
		Button btnYes = (Button) inputPwdDialog.getWindow().findViewById(R.id.dialog_continue_btn_yes);
		((TextView) inputPwdDialog.getWindow().findViewById(R.id.dialog_edittext_tv_infoBefore)).setText("");
		((TextView) inputPwdDialog.getWindow().findViewById(R.id.dialog_edittext_tv_infoBehind)).setText("");
		((TextView) inputPwdDialog.getWindow().findViewById(R.id.dialog_deittext_tv_titleTop)).setText("请输入您的500WAN账户密码");
		((TextView) inputPwdDialog.getWindow().findViewById(R.id.dialog_deittext_tv_title)).setText("用户名：" + UserInfo.getUserInfo().getUserName());

		final EditText edtPwd = (EditText) inputPwdDialog.getWindow().findViewById(R.id.dialog_continuebuy_et_fenShu);
		edtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
		btnYes.setText("确定");
		btnYes.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (edtPwd.getText() != null && edtPwd.getText().toString() != "") {
					String strPwd = edtPwd.getText().toString();
					if (strPwd.length() != 32) {
						strPwd = MD5.md5(strPwd);
					}
					if (strPwd.equals(UserInfo.getUserInfo().getUserPwd())) {
						inputPwdDialog.cancel();
						isShowInputDialog = false;
						cbxAccountProtect.setChecked(false);
						UserInfo.getUserInfo().setAccountProtectState(false);
						updateAccountProtectState(UNUSE_PROTECT);
					} else {
						Toast.makeText(OptionAct.this, "密码错误", Toast.LENGTH_SHORT).show();
						edtPwd.setText(null);
					}
				} else {
					Toast.makeText(OptionAct.this, "密码不能为空", Toast.LENGTH_SHORT).show();
				}
			}
		});
		Button btnNo = (Button) inputPwdDialog.getWindow().findViewById(R.id.dialog_continue_btn_no);
		btnNo.setText("取消");
		btnNo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				inputPwdDialog.cancel();
			}
		});
		inputPwdDialog.show();
	}

}